package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    //@Scheduled(cron = "0 * * * * ?")
    public void processTimeOutOder(){
        try{

            LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

            List<Orders> list =  ordersMapper.getByStatusAndTime(Orders.PENDING_PAYMENT, time);
            if(null != list && list.size() > 0){
                list.forEach(order -> {
                    order.setStatus(Orders.CANCELLED);
                    order.setCancelReason("订单超时 系统自动取消");
                    order.setCancelTime(LocalDateTime.now());

                    ordersMapper.update(order);
                });
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

//    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void processDeloverOrder(){
        try {
            log.info("更新订单状态为已完成");
            LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
            List<Orders> list = ordersMapper.getByStatusAndTime(Orders.DELIVERY_IN_PROGRESS, time);
            if(null != list && list.size() > 0){
                list.forEach(orders -> {
                    orders.setStatus(Orders.COMPLETED);

                    ordersMapper.update(orders);
                });
            }

        }catch (Exception e){
            log.error(e.getMessage());
        }
    }
}
